﻿using Diebold.Common.Log;
using TrialManagmentTool.Helper;
using TrialManagmentTool.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using Tencent;

namespace TrialManagmentTool.Controllers
{
    public class WeiXinController : Controller
    {
        string sToken = ConfigurationManager.AppSettings["Token"].ToString();
        string sCorpID = ConfigurationManager.AppSettings["CorpID"].ToString();
        string sEncodingAESKey = ConfigurationManager.AppSettings["EncodingAESKey"].ToString();
        WXBizMsgCrypt wxcpt;
        WeChatHelper wechatHelp = new WeChatHelper();
        Wxmessage msg = new Wxmessage();

        //
        // GET: /WeiXin/

        public void Index()
        {
            wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);
            LogManager.Debug("GetRequest,Type", Request.HttpMethod + Request.Url);
            if (Request.HttpMethod == "GET")
            {
                if (string.IsNullOrEmpty(Request.QueryString["echoStr"])) { Response.End(); }
                string sVerifyMsgSig = Request.QueryString["msg_signature"].ToString();
                string sVerifyTimeStamp = Request.QueryString["timestamp"].ToString();
                string sVerifyNonce = Request.QueryString["nonce"].ToString();
                string sVerifyEchoStr = Request.QueryString["echostr"].ToString();
                int ret = 0;
                string sEchoStr = "";
                ret = wxcpt.VerifyURL(sVerifyMsgSig, sVerifyTimeStamp, sVerifyNonce, sVerifyEchoStr, ref sEchoStr);
                if (!string.IsNullOrEmpty(sEchoStr))
                {
                    Response.Write(sEchoStr);
                    Response.End();
                }
            }
            else
            {
                //解密操作，根据Sample.cs
                try
                {
                    msg = ConvertMsgToObject();
                    ResponseUserRequest(msg);
                }
                catch (Exception ex)
                {
                    LogManager.Debug("Weixin-Index", ex.ToString() + ex.InnerException.ToString());
                }
            }
        }

        /// <summary>
        /// 将POST过来的数据转化成实体对象
        /// </summary>
        /// <param name="msgBody"></param>
        /// <returns></returns>
        private Wxmessage ConvertMsgToObject(string msgBody = "")
        {
            if (string.IsNullOrWhiteSpace(msgBody))
            {
                Stream s = System.Web.HttpContext.Current.Request.InputStream;
                byte[] b = new byte[s.Length];
                s.Read(b, 0, (int)s.Length);
                msgBody = Encoding.UTF8.GetString(b);
            }
            string msg_signature = Request.QueryString["msg_signature"];
            string timestamp = Request.QueryString["timestamp"];
            string nonce = Request.QueryString["nonce"];
            string sMsg = "";  // 解析之后的明文
            int flag = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, msgBody, ref sMsg);
            if (flag == 0)
            {
                msgBody = sMsg;
            }
            else
            {
                LogManager.Debug("Decrypt-Fail", flag.ToString());
            }

            if (!string.IsNullOrWhiteSpace(msgBody))
            {
                //把解密之后的字符串转换成XML格式处理，并形成一个类
                XmlDocument doc = null;
                XmlNode node = null;

                doc = new XmlDocument();
                doc.LoadXml(msgBody);//解密后才是需要处理的XML数据，读取XML字符串
                XmlElement rootElement = doc.DocumentElement;
                XmlNode msgTypeNode = rootElement.SelectSingleNode("MsgType");//获取字符串中的消息类型
                node = rootElement.SelectSingleNode("MsgType");
                if (node != null)
                {
                    msg.MsgType = node.InnerText;
                }
                node = rootElement.SelectSingleNode("FromUserName");
                if (node != null)
                {
                    msg.FromUserName = node.InnerText;
                }
                node = rootElement.SelectSingleNode("AgentID");
                if (node != null)
                {
                    msg.AgentID = Convert.ToInt32(node.InnerText);
                }
                node = rootElement.SelectSingleNode("ToUserName");
                if (node != null)
                {
                    msg.ToUserName = node.InnerText;
                }
                node = rootElement.SelectSingleNode("CreateTime");
                if (node != null)
                {
                    msg.CreateTime = node.InnerText;
                }
                node = rootElement.SelectSingleNode("MsgId");
                if (node != null)
                {
                    msg.MsgId = node.InnerText.Trim();
                }

                node = rootElement.SelectSingleNode("Content");
                if (node != null)
                {
                    msg.Content = node.InnerText.Trim();
                }
                node = rootElement.SelectSingleNode("Event");
                if (node != null)
                {
                    msg.Event = node.InnerText;
                }
                node = rootElement.SelectSingleNode("EventKey");
                if (node != null)
                {
                    msg.EventKey = node.InnerText;
                }
            }
            return msg;

        }

        /// <summary>
        /// 处理用户信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public void ResponseUserRequest(Wxmessage msg)
        {
            string MsgType = msg.MsgType.Trim().ToLower();
            switch (MsgType)
            {
                case "text"://接收普通消息 text消息
                    string content = msg.Content;
                    if (content != null)
                    {
                        wechatHelp.SendTextMessage(msg);
                    }
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 获取登陆code
        /// </summary>
        public void GetUserInfo()
        {
            string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect",
               sCorpID, "http://zhangyan.10301.pc5s.cn/Weixin/WeixinGetUserInfo", "snsapi_base", "Test");
            Response.Redirect(url);

        }
        /// <summary>
        /// 获取登陆用户信息
        /// </summary>
        /// <returns></returns>
        public ActionResult WeixinGetUserInfo()
        {
            string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token={0}&code={1}", wechatHelp.GetToken(), Request.QueryString["code"]);
            HttpWebRequest hwr = WebRequest.Create(url) as HttpWebRequest;
            hwr.Method = "POST";
            hwr.ContentType = "application/x-www-form-urlencoded";
            var result = hwr.GetResponse() as HttpWebResponse;
            StreamReader reader = new StreamReader(result.GetResponseStream(), Encoding.UTF8);
            string content = reader.ReadToEnd();
            reader.Close();
            reader.Dispose();
            UserWXModel userWXModel = JsonHelper.ParseFromJson<UserWXModel>(content);
            if (userWXModel.UserId != null)
            {
                //企业用户
                return View("Index");
            }
            else
            {
                //To 绑定页面
                return View("Error");
            }
        }
    }
}
